package dal

import (
	"fmt"

	. "7qule.com/sd3/CrossServer/src/bll/kuangzhan/model"
	baseDal "7qule.com/sd3/CrossServer/src/dal"
)

// 镖局信息访问结构
type globalKuangzhanDal struct{}

// 访问结构对象
var GlobalKuangzhanDal = new(globalKuangzhanDal)

// 初始化
func init() {
	// 注册到同步对象中
	baseDal.GetSyncMgr().RegisterSyncObj(GlobalKuangzhanDal.TableName())
}

// TableName 表名
func (this *globalKuangzhanDal) TableName() string {
	return "g_kuangzhan"
}

// GetData 从数据库获取玩家数据
// dataContainer:玩家对象
// 返回值:
// interface{}:获取到的数据
// error:错误信息
func (this *globalKuangzhanDal) GetData() ([]*GlobalKuangzhan, error) {
	sql := "SELECT `LayerId`,`PositionId`,`PlayerId`,`GuildId` FROM `g_kuangzhan`;"

	db := baseDal.GetGameDB().DB()
	execResult, err := db.Query(sql)
	if err != nil {
		baseDal.WriteLog("GlobalKuangzhanDal", err)

		return nil, err
	}

	defer execResult.Close()

	// 读取数据
	var result = make([]*GlobalKuangzhan, 0, 16)
	for execResult.Next() {
		var tempNewItem = NewGlobalKuangzhan2()
		err = execResult.Scan(
			&tempNewItem.LayerId,
			&tempNewItem.PositionId,
			&tempNewItem.PlayerId,
			&tempNewItem.GuildId)

		if err != nil {
			baseDal.WriteLog("GlobalKuangzhanDal", err)
			return nil, err
		}

		result = append(result, tempNewItem)
	}

	return result, nil
}

// Insert 插入数据
// dataContainer:玩家对象
// redisData:redis数据
// data:操作的数据项
func (this *globalKuangzhanDal) Insert(data *GlobalKuangzhan) {
	sql := fmt.Sprintf("INSERT INTO `g_kuangzhan` (`PlayerId`,`LayerId`,`PositionId`,`GuildId`) VALUES ('%v', '%v', %v, '%v') ;",
		data.PlayerId,
		data.LayerId,
		data.PositionId,
		data.GuildId)

	baseDal.GetGameDB().Exec(sql)
}

// Update 更新数据
// dataContainer:玩家对象
// redisData:最新redis数据
// data:操作的数据项
func (this *globalKuangzhanDal) Update(data *GlobalKuangzhan) {
	sql := fmt.Sprintf("UPDATE `g_kuangzhan` SET  `PlayerId`='%v',`GuildId`='%v' WHERE `LayerId`= '%v' AND `PositionId`='%v';",
		data.PlayerId,
		data.GuildId,
		data.LayerId,
		data.PositionId)
	baseDal.GetGameDB().Exec(sql)
}

// Delete 删除数据
// dataContainer:玩家对象
// redisData:最新redis数据
// data:操作的数据项
func (this *globalKuangzhanDal) Delete(data *GlobalKuangzhan) {
	sql := fmt.Sprintf("DELETE FROM g_kuangzhan where`LayerId`='%v' AND `PositionId`='%v' ;", data.LayerId, data.PositionId)

	baseDal.GetGameDB().Exec(sql)
}

//
// DeleteLayer
// @Description: 删除一层数据
// @receiver this
// @param LayerId 层数id
//
func (this *globalKuangzhanDal) DeleteLayer(LayerId int32) {
	sql := fmt.Sprintf("DELETE FROM g_kuangzhan where`LayerId`='%v' ;", LayerId)

	baseDal.GetGameDB().Exec(sql)
}
